<?php

class PostContentParser
{

    private $rawContent;
    private $sourceUrl;

    function __construct($rawContent)
    {
        $this->rawContent = $rawContent;
    }

    public function GetPureContent()
    {
        $noBrContent = RssSpiderUtils::br2nl($this->rawContent);
        return trim(strip_tags($noBrContent));
    }

    /**
     * @param $sourceUrl
     * @return null|RssPostImage
     */
    public function GetPostImage($sourceUrl)
    {
        $this->sourceUrl = $sourceUrl;

        $rssPostImage = null;
        if ( empty($this->rawContent) )
        {
            return null;
        }

        $domDoc = new DOMDocument();
        libxml_use_internal_errors(true);
        $domDoc->loadHTML($this->rawContent);

        $xPathHelper = new XPathHelper($domDoc);
        $imgElements = $xPathHelper->GetNodes("//img");

        foreach ($imgElements as $imgElement)
        {
            $rssPostImage = $this->GetImageFromElement($imgElement);
            if ( $rssPostImage )
            {
                break;
            }
        }

        return $rssPostImage;
    }

    /**
     * @param DOMElement $imgElement
     * @return null|RssPostImage
     */
    private function GetImageFromElement( DOMElement $imgElement )
    {
        $rssPostImage = null;

        $url = $imgElement->getAttribute("src");
        $url = $this->GetAbsolutePath($url);
        $imgData = RssSpiderUtils::GetResource($url);

        try
        {
            $thumbnailGenerator = new ThumbnailGenerator($imgData);
            if ($thumbnailGenerator->IsSourceValid())
            {
                $rssPostImage = new RssPostImage();
                $rssPostImage->SetLink($url);

                $image = $thumbnailGenerator->Generate();
                $rssPostImage->SetImage($image);

                $title = $imgElement->getAttribute("title");
                $rssPostImage->SetTitle($title);
            }
        }
        catch (ThumbnailGeneratorException $e)
        {
            //do nothing
        }

        return $rssPostImage;
    }

    private function GetAbsolutePath( $path )
    {
        $resultPath = $path;
        if ( !UrlHelper::IsPathAbsolute($path) )
        {
            $sourceUrlParts = parse_url($this->sourceUrl);
            $scheme = ( isset($sourceUrlParts['scheme']) ) ? $sourceUrlParts['scheme'] : "";
            $host = ( isset($sourceUrlParts['host']) ) ? $sourceUrlParts['host'] : "";
            $port = ( isset($sourceUrlParts['port']) ) ? ":" . $sourceUrlParts['port'] : "";
            $resultPath = $scheme . "://" . $host . $port . $path;
        }
        return $resultPath;
    }

}

?>